#include "server.hpp"
#include <memory>
#include <assert.h>
#include <fstream>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

#define ROOT "." // httpd都有自己的web根目录
// 如果客户端只请求了一个,我们返回默认首页
#define HOMEPAGE "index.html"

void HandlerHttpRequest(int sockfd)
{
    // 1、读取请求
    char buff[10240];
    ssize_t s = recv(sockfd, buff, sizeof(buff) - 1, 0);
    if (s > 0)
    {
        buff[s] = 0;
        std::cout << buff << "--------------\n"
                  << std::endl;
    }

    std::vector<std::string> v_line;
    Util::cutString(buff, "\r\n", &v_line);

    std::vector<std::string> v_block;
    Util::cutString(v_line[0], "\r\n", &v_block);

    std::string file = v_block[1]; // 资源路径
    std::string target = ROOT;
    if (file == "/")
        file = "/index.html";
    target += file;
    std::cout << target << std::endl;
    target.insert(target.begin(), '.');

    std::string content;
    std::ifstream in(target);
    if (!in.is_open())
    {
        std::string line;
        while (std::getline(in, line))
        {
            content += line;
        }
        in.close();
    }

    // 2、构建http响应
    std::string HttpResponse;
    if (content.empty())
    {
        HttpResponse = "HTTP/1.1 404 not find\r\n";
        HttpResponse += "Location: https://www.baidu.com/\r\n";
    }
    else
    {
        HttpResponse = "HTTP/1.1 20 OK\r\n";
        HttpResponse += ("Content_Type: text/html\r\n");
        HttpResponse += ("Content_Length: " +
                         std::to_string(content.size()) + "\r\n");
        HttpResponse += "Set-Cookie:这个Cookie\r\n";
    }

    HttpResponse += "\r\n";
    HttpResponse += content;
    send(sockfd, HttpResponse.c_str(), HttpResponse.size(), 0);
}

int main(int argc, char *argv[])
{
    if (argc != 2)
    {
        Usage(argv[0]);
        exit(1);
    }

    std::unique_ptr<HttpServer> httpserver(new HttpServer(atoi(argv[1]), HandlerHttpRequest));
    httpserver->Start();

    return 0;
}